<template>
  <md-popup id="mapview" :value="true" position="bottom" :has-mask="false" prevent-scroll>
    <div class="container">
      <div id="searcher">
        <div class="city-name">{{isStart?getRoute.start_route:getRoute.end_route}}</div>
        <input @focus="onSearcherFocus" type="text" v-model="searchValue" class="searcher-input" ref="searcher-input" :placeholder="hintString" />
        <div class="searcher-btn" @click="close">取消</div>
      </div>
      <amap
        class="amap"
        ref="amap"
        :mode="mode"
        :fences="getFences"
        :stations="getStations"
        @select="onMapSelect"
        @dragstart="onMapStartDrag"
        :centerMode="centerMode"
        :center="getCenter"
        :isStart="isStart"
      ></amap>
      <div id="search-result" v-if="selectedAddress">
        <img :src="isStart?syncStartIcon:syncEndIcon" class="sync-icon" />
        <div class="address-field">
          <div class="row centered">
            <div class="main-string text-ellipsis">{{selectedAddress.stationName}}</div>
            <div v-if="selectedAddress.stationId" class="tag">乘车点</div>
          </div>
          <div class="sub-string text-ellipsis">{{selectedAddress.position}}</div>
        </div>
        <md-button class="confirm-btn" @click="confirm">确定</md-button>
      </div>
      <search-box
        v-show="showBox"
        :mode="mode"
        :stations="getStations"
        :history="mode=='1'?[]:getHistoryStations"
        :searchs="searchList"
        v-model="searchValue"
        @select="onItemSelect"
      ></search-box>
    </div>
  </md-popup>
</template>

<script>
import '@/assets/svgs/bqbq_icon.svg';
import { mapGetters } from 'vuex';
import { Popup, Icon, Button, Dialog } from 'mand-mobile';
import MapTool from './MapTool';
import { PINCHE, BAOCHE, OPT_TYPE_ZHANDIAN, OPT_TYPE_WEILAN, OPT_TYPE_BOTH } from './types';
import { IS_OUT_RANGE, LOCATION_HAS_BAO_SERVICE } from '@/store/actions.types';
import { SET_PIN_START_INFO, SET_PIN_END_INFO, SET_BAO_START_INFO, SET_BAO_END_INFO } from '@/store/mutations.types';
import SearchBox from './search/SearchBox';
export default {
  name: 'map-view',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    mode: {
      // 地图类型：1:站点、2:围栏、3:共存
      type: String,
      default: '1'
    },
    type: {
      // 1:拼车、2:包车
      type: String,
      default: '1'
    },
    isStart: {
      // 起点还是终点
      type: Boolean,
      default: false
    },
    appendTo: {
      default: () => document.body
    }
  },
  watch: {
    searchValue: 'onValueChange'
  },
  data() {
    return {
      searchValue: '',
      syncStartIcon: require('@/assets/imgs/snyc_shangche_icon.png'),
      syncEndIcon: require('@/assets/imgs/snyc_xiache_icon.png'),
      selectedAddress: null,
      showBox: false,
      autoComplete: null,
      searchList: null,
      isItemFromList: false
    };
  },
  created() {
    AMap.plugin('AMap.Autocomplete', () => {
      let autoOptions = {
        city: this.isStart ? this.getRoute.start_code : this.getRoute.end_code,
        citylimit: true
      };
      this.autoComplete = new AMap.Autocomplete(autoOptions);
    });
    this.$store.dispatch('getHistoryStations', {
      route_id: this.getRoute.route_id,
      city: this.isStart ? this.getRoute.start_route : this.getRoute.end_route,
      is_start: this.isStart ? '1' : '2', // 1：起点 ，2：终点
      order_type: this.type // 1：拼车，2：包车
    });
  },
  methods: {
    close() {
      if (this.showBox) {
        this.showBox = false;
      } else {
        this.$emit('close');
      }
    },
    onMapSelect(item) {
      if (item.adsorption) {
        this.selectedAddress = item;
        this.$refs.amap.createTextTip(item.coordinate, this.isStart ? '在这里上车' : '在这里下车');
        return;
      }
      if (item.isStation) {
        this.selectedAddress = item;
        this.$refs.amap.createTextTip(item.coordinate, this.isStart ? '在这里上车' : '在这里下车');
        return;
      }
      if (this.isItemFromList) {
        return;
      }
      const coord = item.coordinate.join(',');
      let params = {
        type: '1', // 1：城际；2：市内；3：顺风车
        routeId: this.getRoute.route_id,
        lnglat: coord,
        orderType: this.type,
        routeType: this.isStart ? '1' : '2'
      };
      this.$store
        .dispatch('getAdsorptionSiteByLnglat', params)
        .then(res => {
          if (res && JSON.stringify(res) != '{}') {
            if (res.adsorption && res.adsorption instanceof Array) {
              if (res.adsorption.length >= 1) {
                this.$refs.amap.createAdsorptionMarkers(res.adsorption, res.siteId);
              }
            }
            if (res.fence != undefined && res.fence != '') {
              // 有吸附点围栏，进行吸附处理
              this.$refs.amap.createAdsorptionFence(res.fence);
            }
          } else {
            // 没有吸附点围栏，无需处理
            this.selectedAddress = item;
            this.$refs.amap.createTextTip(item.coordinate, this.isStart ? '在这里上车' : '在这里下车');
            this.$refs.amap.clearAdsorption();
          }
        })
        .catch(reason => {
          console.error(reason);
          this.selectedAddress = item;
          this.$refs.amap.createTextTip(item.coordinate, this.isStart ? '在这里上车' : '在这里下车');
        });
      // this.selectedAddress = item;
      // this.$refs.amap.setCenter(this.selectedAddress.coordinate);
    },
    onSearcherFocus(event) {
      this.showBox = true;
    },
    onItemSelect(item) {
      this.showBox = false;
      if (item.stationId) {
        this.isItemFromList = true;
      }
      this.$refs.amap.setCenter(item.coordinate);
      this.selectedAddress = item;
      this.$refs.amap.highLightStation(item);
    },
    onMapStartDrag() {
      this.isItemFromList = false;
      this.$refs.amap.closeTextTip();
    },
    onValueChange(value) {
      if (!this.autoComplete) {
        return;
      }
      this.autoComplete.search(value, (status, result) => {
        if (typeof result !== 'string') {
          if (result.tips && result.tips.length > 0) {
            let arr = [];
            result.tips.forEach((item, index) => {
              if (!item.location) {
                return;
              }
              if (!this.$refs.amap.isContain(item.location)) {
                return;
              }
              let obj = {
                stationName: item.name,
                position: item.district + item.address,
                coordinate: [item.location.lng, item.location.lat]
              };
              arr.push(obj);
            });
            this.searchList = arr;
          }
        }
      });
    },
    confirm() {
      if (this.mode === '1') {
        this.submit();
      } else if (this.selectedAddress.stationId && this.mode === '3') {
        this.submit();
      } else {
        let param = {};
        if (this.isStart) {
          param.route_id = this.getRoute.route_id;
          param.origin_coord = this.coordToString(this.selectedAddress.coordinate);
        } else {
          param.route_id = this.getRoute.route_id;
          param.dest_coord = this.coordToString(this.selectedAddress.coordinate);
        }
        if (this.type === '1') {
          param.type = 1;
        } else if (this.type === '2') {
          param.type = 2;
        }
        param.site_id = this.selectedAddress.routeStationId;
        param.isStart = this.isStart;
        this.$store.dispatch(LOCATION_HAS_BAO_SERVICE, param).then(res => {
          if (res.flag === '1') {
            // 拼可以、包可以
            this.submit(res.flag);
          } else if (res.flag === '2') {
            // 拼可以、包不可以
            if (this.type === '1') {
              this.submit(res.flag);
            } else {
              if (this.hasPinService && this.isStart ? this.hasPinStartFence : this.hasPinEndFence) {
                Dialog.confirm({
                  title: '温馨提示',
                  content: '当前选择的地址不在包车服务范围，您可使用拼车服务',
                  confirmText: '去拼车',
                  onConfirm: () => {
                    if (this.isStart) {
                      this.$store.commit(SET_PIN_START_INFO, this.selectedAddress);
                    } else {
                      this.$store.commit(SET_PIN_END_INFO, this.selectedAddress);
                    }
                    this.$emit('gotoPinService');
                  }
                });
              } else {
                Dialog.alert({
                  icon: 'bqbq_icon',
                  content: '非常抱歉！请在红色围栏内重新选择上车点',
                  confirmText: '我知道了'
                });
              }
            }
          } else if (res.flag === '3') {
            // 拼不可以、包可以
            if (this.type === '2') {
              this.submit(res.flag);
            } else {
              if (this.hasBaoService && this.isStart ? this.hasBaoStartFence : this.hasBaoEndFence) {
                Dialog.confirm({
                  title: '温馨提示',
                  content: '当前选择的地址不在拼车服务范围，您可使用包车服务',
                  confirmText: '去包车',
                  onConfirm: () => {
                    if (this.isStart) {
                      this.$store.commit(SET_BAO_START_INFO, this.selectedAddress);
                    } else {
                      this.$store.commit(SET_BAO_END_INFO, this.selectedAddress);
                    }
                    this.$emit('gotoBaoService');
                  }
                });
              } else {
                Dialog.alert({
                  icon: 'bqbq_icon',
                  content: '非常抱歉！请在红色围栏内重新选择上车点',
                  confirmText: '我知道了'
                });
              }
            }
          } else if (res.flag === '4') {
            // 都不可以
            Dialog.alert({
              icon: 'bqbq_icon',
              content: '非常抱歉！请在红色围栏内重新选择上车点',
              confirmText: '我知道了'
            });
          }
        });
      }
    },
    submit(flag = undefined) {
      console.log('地图选点FLAG：', flag);
      if (this.type === '1') {
        // 拼车模式下
        if (this.isStart) {
          // 起点
          if (flag === '1') {
            // 既可以拼车也可以包车
            this.$store.commit(SET_PIN_START_INFO, this.selectedAddress);
            this.$store.commit(SET_BAO_START_INFO, this.selectedAddress);
          } else {
            // 只能拼车
            this.$store.commit(SET_PIN_START_INFO, this.selectedAddress);
            this.$store.commit(SET_BAO_START_INFO, null);
          }
        } else {
          // 终点
          if (flag === '1') {
            // 既可以拼车也可以包车
            this.$store.commit(SET_PIN_END_INFO, this.selectedAddress);
            this.$store.commit(SET_BAO_END_INFO, this.selectedAddress);
          } else {
            this.$store.commit(SET_PIN_END_INFO, this.selectedAddress);
            this.$store.commit(SET_BAO_END_INFO, null);
          }
        }
      } else {
        // 包车模式下
        if (this.isStart) {
          // 起点
          if (flag === '1') {
            // 既可以拼车也可以包车
            this.$store.commit(SET_PIN_START_INFO, this.selectedAddress);
            this.$store.commit(SET_BAO_START_INFO, this.selectedAddress);
          } else {
            // 只可以
            this.$store.commit(SET_PIN_START_INFO, null);
            this.$store.commit(SET_BAO_START_INFO, this.selectedAddress);
          }
        } else {
          // 终点
          if (flag) {
            this.$store.commit(SET_PIN_END_INFO, this.selectedAddress);
            this.$store.commit(SET_BAO_END_INFO, this.selectedAddress);
          } else {
            this.$store.commit(SET_PIN_END_INFO, null);
            this.$store.commit(SET_BAO_END_INFO, this.selectedAddress);
          }
        }
      }
      this.$emit('confirm');
    },
    coordToString(coordinate) {
      return coordinate[0] + ',' + coordinate[1];
    }
  },
  components: {
    [Popup.name]: Popup,
    [MapTool.name]: MapTool,
    [Icon.name]: Icon,
    [Button.name]: Button,
    [SearchBox.name]: SearchBox
  },
  mounted() {
    if (this.appendTo) {
      this.appendTo.appendChild(this.$el);
    }
  },
  beforeDestroy() {
    if (this.appendTo) {
      this.appendTo.removeChild(this.$el);
    }
  },
  computed: {
    hintString() {
      return this.isStart ? '您从哪儿上车' : '您要去哪儿';
    },
    getFences() {
      if (this.mode === OPT_TYPE_WEILAN || this.mode === OPT_TYPE_BOTH) {
        if (this.isStart) {
          // 起点还是终点
          if (this.type === PINCHE) {
            // 拼车还是包车
            return this.pinStartFences;
          } else if (this.type === BAOCHE) {
            return this.baoStartFences;
          }
        } else {
          if (this.type === PINCHE) {
            // 拼车还是包车
            return this.pinEndFences;
          } else if (this.type === BAOCHE) {
            return this.baoEndFences;
          }
        }
      }
    },
    getStations() {
      if (this.mode === OPT_TYPE_ZHANDIAN || this.mode === OPT_TYPE_BOTH) {
        if (this.isStart) {
          if (this.type === PINCHE) {
            return this.pinStartStations;
          } else {
            return this.baoStartStations;
          }
        } else {
          if (this.type === PINCHE) {
            return this.pinEndStations;
          } else {
            return this.baoEndStations;
          }
        }
      }
    },
    centerMode() {
      let mode = '0';
      if (this.mode === OPT_TYPE_ZHANDIAN) {
        return mode;
      }
      if (this.gpsStatus === '2') {
        mode = '2';
      } else {
        mode = '1';
      }
      return mode;
    },
    getCenter() {
      let center = null;
      if (this.isStart) {
        if (this.type === PINCHE) {
          center = this.pinStartMapCenter;
        } else {
          center = this.baoStartMapCenter;
        }
      } else {
        if (this.type === PINCHE) {
          center = this.pinEndMapCenter;
        } else {
          center = this.baoEndMapCenter;
        }
      }
      if (this.gpsStatus === '2') {
        center = this.getCurrentLocation.coordinate;
      }
      if (center) {
        if (center.length < 2) {
          // 后台中心点没有设定
          center = null;
        }
      }
      return center;
    },
    hasPinService() {
      if (this.getRoute) {
        return this.getRoute.service_type.indexOf('1') > -1;
      } else {
        return false;
      }
    },
    hasBaoService() {
      if (this.getRoute) {
        return this.getRoute.service_type.indexOf('2') > -1;
      } else {
        return false;
      }
    },
    hasBaoStartFence() {
      return this.getRoute.bao_opt_type_start === '2' || this.getRoute.bao_opt_type_start === '3';
    },
    hasBaoEndFence() {
      return this.getRoute.bao_opt_type_end === '2' || this.getRoute.bao_opt_type_end === '3';
    },
    hasPinStartFence() {
      return this.getRoute.pin_opt_type_start === '2' || this.getRoute.pin_opt_type_start === '3';
    },
    hasPinEndFence() {
      return this.getRoute.pin_opt_type_end === '2' || this.getRoute.pin_opt_type_end === '3';
    },
    ...mapGetters([
      'getCurrentLocation',
      'getRoute',
      'pinStartFences',
      'pinEndFences',
      'pinStartStations',
      'pinEndStations',
      'baoStartFences',
      'baoEndFences',
      'baoStartStations',
      'baoEndStations',
      'pinStartMapCenter',
      'pinEndMapCenter',
      'baoStartMapCenter',
      'baoEndMapCenter',
      'getHistoryStations',
      'gpsStatus'
    ])
  }
};
</script>

<style lang="stylus">
#mapview {
  .md-popup-mask {
    z-index: 100;
  }

  .container {
    width: 100vw;
    height: 100vh;
    background-color: #fff;

    .amap {
      width: 100vw;
      height: calc(100vh - 88px);
    }

    #searcher {
      background-color: #F8F8F8;
      font-size: 28px;
      height: 88px;
      padding-left: 30px;
      padding-right: 30px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;

      .city-name {
        min-width: 3em;
        max-width: 8em;
        color: #666;
        padding-right: 20px;
        border-right: 1px solid #E0E0E0;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .searcher-input {
        padding-left: 20px;
        border: 0px;
        outline: none;
        background-color: transparent;
        flex: 1;
      }

      .searcher-btn {
        color: #888888;
        padding-left: 20px;
      }
    }

    #search-result {
      width: 710px;
      height: 120px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: fixed;
      background-color: #fff;
      bottom: 20px;
      left: 20px;

      .sync-icon {
        width: 40px;
        height: 48px;
        margin-left: 20px;
      }

      .address-field {
        flex: 1;
        margin-left: 20px;

        .main-string {
          font-size: 26px;
          font-weight: 400;
          max-width: 16em;
          color: color-text-base;
        }

        .tag {
          background-color: #FF6917;
          width: 72px;
          height: 28px;
          color: #fff;
          font-size: 20px;
          line-height: 28px;
          margin-left: 10px;
          text-align: center;
          border-radius: 4px;
          padding: 0px 6px;
          vertical-align: middle;
        }

        .sub-string {
          font-size: 22px;
          font-weight: 400;
          max-width: 20em;
          color: color-text-caption;
        }
      }

      .confirm-btn {
        width: 160px;
        height: 68px;
        font-size: 30px;
        margin-right: 20px;
      }
    }
  }
}
</style>
